'use client';

import React, { useState } from 'react';
import { Card, Form, Input, Button, Space, DatePicker, Checkbox, message } from 'antd';
import { KeyOutlined, GlobalOutlined, LaptopOutlined, SafetyCertificateOutlined, CheckCircleOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';

export default function LicenseGenerator() {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [generating, setGenerating] = useState(false);
  const [verifying, setVerifying] = useState(false);
  const [verificationResult, setVerificationResult] = useState<{valid: boolean, reason: string} | null>(null);
  const [hardwareInfo, setHardwareInfo] = useState<any>(null); // 保存硬件信息用于下载

  /**
   * 获取硬件信息
   */
  const getHardwareInfo = async () => {
    setLoading(true);
    try {
      // 调用API获取硬件信息
      const response = await fetch('/api/license/generate', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      const result = await response.json();
      
      if (result.status === 200 && result.data) {
        // 设置表单值
        form.setFieldsValue({
          cpuId: result.data.cpuId,
          cpuName: result.data.cpuName,
          macAddress: result.data.macAddress,
          publicIp: '',
          admin: false
        });
        
        // 保存硬件信息用于下载
        setHardwareInfo(result.data);

        console.log('硬件信息:', result.data);
        
        message.success('硬件信息获取成功');
      } else {
        message.error(result.message || '获取硬件信息失败');
      }
    } catch (error) {
      console.error('获取硬件信息失败:', error);
      message.error('获取硬件信息失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 下载硬件信息
   */
  const downloadHardwareInfo = () => {
    if (!hardwareInfo) {
      message.warning('请先获取硬件信息');
      return;
    }
    
    // 触发下载
    const element = document.createElement('a');
    const file = new Blob([JSON.stringify(hardwareInfo, null, 2)], {type: 'application/json'});
    element.href = URL.createObjectURL(file);
    element.download = 'hardware-info.json';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  };

  /**
   * 生成License
   */
  const generateLicense = async (values: any) => {
    setGenerating(true);
    try {
      // 构建请求数据
      const { cpuId, cpuName, macAddress, publicIp, expiryDate, admin } = values;
      console.log('License数据:', values);
      const licenseData = {
        cpuId,
        cpuName,
        macAddress,
        publicIp,
        expiryDate: expiryDate.format('YYYY-MM-DD'),
        admin
      };
      
      // 发送请求生成License
      const response = await fetch('/api/license/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(licenseData)
      });
      
      const result = await response.json();
      
      if (result.status === 200) {
        message.success('License生成成功');
        // 触发下载
        const element = document.createElement('a');
        const file = new Blob([JSON.stringify(result.data, null, 2)], {type: 'application/json'});
        element.href = URL.createObjectURL(file);
        element.download = 'license.json';
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
      } else {
        message.error(result.message || 'License生成失败');
      }
    } catch (error) {
      console.error('生成License失败:', error);
      message.error('生成License失败，请稍后重试');
    } finally {
      setGenerating(false);
    }
  };

  /**
   * 验证License
   */
  const verifyLicense = async () => {
    setVerifying(true);
    setVerificationResult(null);
    try {
      const response = await fetch('/api/license/status');
      const result = await response.json();
      
      if (result.status === 200) {
        setVerificationResult({ valid: true, reason: result.message });
        message.success(result.message);
      } else {
        setVerificationResult({ valid: false, reason: result.message });
        message.error(result.message);
      }
    } catch (error) {
      console.error('验证License失败:', error);
      message.error('验证License失败，请稍后重试');
    } finally {
      setVerifying(false);
    }
  };

  return (
    <>
      <Card title="生成License" extra={<Button type="primary" onClick={getHardwareInfo} loading={loading}>获取硬件信息</Button>} style={{ marginBottom: 24 }}>
        <Form
          form={form}
          layout="vertical"
          onFinish={generateLicense}
        >
          <Form.Item
            label="CPU ID"
            name="cpuId"
            rules={[{ required: true, message: '请输入CPU ID' }]}
          >
            <Input prefix={<LaptopOutlined />} placeholder="请输入CPU ID" />
          </Form.Item>

          <Form.Item
            label="CPU Name"
            name="cpuName"
            rules={[{ required: true, message: '请输入CPU Name' }]}
          >
            <Input prefix={<LaptopOutlined />} placeholder="请输入CPU Name" />
          </Form.Item>
          
          <Form.Item
            label="MAC地址"
            name="macAddress"
            rules={[{ required: true, message: '请输入MAC地址' }]}
          >
            <Input prefix={<KeyOutlined />} placeholder="请输入MAC地址" />
          </Form.Item>
          
          <Form.Item
            label="公网IP"
            name="publicIp"
            rules={[{ required: false, message: '请输入公网IP' }]}
          >
            <Input prefix={<GlobalOutlined />} placeholder="请输入公网IP" />
          </Form.Item>
          
          <Form.Item
            label="过期日期"
            name="expiryDate"
            rules={[{ required: true, message: '请选择过期日期' }]}
          >
            <DatePicker 
              style={{ width: '100%' }} 
              placeholder="请选择过期日期"
              format="YYYY-MM-DD"
              disabledDate={(current) => current && current < dayjs().endOf('day')}
            />
          </Form.Item>
          
          <Form.Item name="admin" label="是否管理员" valuePropName="checked">
            <Checkbox>是否管理员</Checkbox>
          </Form.Item>
          
          <Form.Item style={{ marginTop: 24, textAlign: 'center' }}>
            <Space size="large">
              <Button 
                htmlType="button"
                onClick={downloadHardwareInfo}
                size="large"
              >
                下载硬件信息
              </Button>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={generating}
                icon={<SafetyCertificateOutlined />}
                size="large"
              >
                生成License
              </Button>
              <Button 
                htmlType="button" 
                onClick={() => form.resetFields()}
                size="large"
              >
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      
      {/* 新增的验证License Card */}
      <Card title="验证License" extra={
        <Button 
          type="primary" 
          onClick={verifyLicense} 
          loading={verifying}
          icon={<CheckCircleOutlined />}
        >
          验证License
        </Button>
      }>
        {verificationResult ? (
          <div style={{ 
            padding: '20px', 
            textAlign: 'center',
            backgroundColor: verificationResult.valid ? '#f6ffed' : '#fff2f0',
            border: `1px solid ${verificationResult.valid ? '#b7eb8f' : '#ffccc7'}`,
            borderRadius: '4px'
          }}>
            <h3 style={{ 
              color: verificationResult.valid ? '#52c41a' : '#ff4d4f',
              marginBottom: '10px'
            }}>
              {verificationResult.valid ? '✓ License 有效' : '✗ License 无效'}
            </h3>
            <p>{verificationResult.reason}</p>
          </div>
        ) : (
          <div style={{ 
            padding: '20px', 
            textAlign: 'center',
            backgroundColor: '#e6f7ff',
            border: '1px solid #91d5ff',
            borderRadius: '4px'
          }}>
            <p>点击"验证License"按钮检查当前License状态</p>
          </div>
        )}
      </Card>
    </>
  );
}